import type { AlovaConf, CompositionError, Data, ServerData } from './types'
import VueHook from 'alova/vue'

import { createAlova } from 'alova'
import GlobalFetch from 'alova/GlobalFetch'

import env from './config'

import { isObject } from 'radash'
import Cookie from 'js-cookie'
// import { useToast } from 'primevue/usetoast'

export const errors = (error: CompositionError) => {
    const msg = error instanceof Error ? error.message : isObject(error) ? error.msg : String(error)
    console.error(msg)
}

const reLogin = () => {
    Cookie.remove('token')
}

const onSuccess: AlovaConf['onSuccess'] = async (response, method) => {
    const { status } = response
    const serverData = (await (method.meta?.blob ? response.blob() : response.json())) as ServerData
    const wrappedData: Data = { ok: false, data: serverData }

    if (status >= 200 && status < 300 && (serverData instanceof Blob || serverData.code === 0)) {
        wrappedData.ok = true
        return wrappedData
    }

    if (!(serverData instanceof Blob)) {
        if (serverData.code === 401) {
            reLogin()
        } else {
            errors(serverData.msg)
        }
    }

    return wrappedData
}

// 网络错误
const onError: AlovaConf['onError'] = (error: Error) => {
    if (error.message.includes('timeout')) {
        errors('请求超时')
    } else if (error.message.includes('Failed to fetch')) {
        errors('网络错误, 请重试')
    } else {
        errors(error.message)
    }

    return { ok: false, data: null }
}

const httpCreate = (baseURL: string, timeout = 6e5) => {
    const alovaInstance = createAlova({
        requestAdapter: GlobalFetch(),
        statesHook: VueHook,
        baseURL: env.apiPath + baseURL,
        timeout,
        responded: {
            onSuccess,
            onError
        }
    })

    return alovaInstance
}

export { httpCreate }
